<template>
  <!-- 首页信息 -->
  <van-nav-bar v-if="home === 'home'" class="home-bar">
    <template #left>
      <van-icon @click="$myRouter.push('/cate')" name="gift-card" class="cate_btn" />
    </template>
    <template #title>
      <van-search @click="$myRouter.push('/search')" autocomplete="off" shape="round" class="search" background="red" placeholder="请输入搜索关键词" />
    </template>
    <template #right>
      <van-icon style="font-size: 24px; color: #ccc;" @click="$myRouter.push('/self')" v-if="$userStore.is_login" name="friends-o" />
      <span v-else @click="$myRouter.push('/login')" class="login_btn">登录</span>
    </template>
  </van-nav-bar>

  <!-- 非首页信息 -->
  <van-nav-bar v-else @click-left="$myRouter.back()" :title="title" left-arrow>
    <template v-if="center === 'search'" #title>
      <van-search
        v-model="searchText"
        :autofocus="true"
        ref="abcd"
        autocomplete="off"
        class="search"
        placeholder="请输入搜索关键词"
        @search="searchHandler"
        @update:model-value="inputHandler"
        @click="$myRouter.push('/search')" />
    </template>
    <template v-if="right === 'search'" #right>
      <van-button @click="searchHandler" size="small" type="danger">搜索</van-button>
    </template>
    <template v-if="right === 'more'" #right>
      ···
    </template>
  </van-nav-bar>
</template>

<script name="sdyHeader" lang="ts" setup>
import { useRouter } from 'vue-router'
import { ref } from 'vue'
import useUserStore from '../store/user'

const $myRouter = useRouter()
const $userStore = useUserStore() as any

// 定义接受参数的接口
interface HeaderInfo {
  right?: string
  center?: string
  title?: string
  home?: string
}

// 定义自定义事件的接口
interface EmitsInfo {
  (e: 'searchText', str: string): void
}

defineProps<HeaderInfo>()

const emits = defineEmits<EmitsInfo>()

// 定义变量, 获取搜索关键字
const searchText = ref<string>('')

// 确认搜索内容
const searchHandler = () => {
  // 按下回车按钮, 带着当前搜索的关键字
  // 条件判断
  if (!searchText.value.trim()) return

  // 把当前搜索关键字存储到 localStorage 内
  // 说明: id 使用一个 随机数字
  const info = {
    wordid: Math.random().toString().slice(-8),
    keyword: searchText.value
  }

  // 拿到 localStorage 内的内容, 把 info 加进去
  // 再把加号 info 的内容从新存储
  const searchList = JSON.parse(window.localStorage.getItem('searchList') || '[]')
  searchList.unshift(info)
  window.localStorage.setItem('searchList', JSON.stringify(searchList))

  // 并且跳转路由到 /list 组件
  $myRouter.replace({ path: '/list', query: { keyword: info.keyword } })
}

// 当我们输入内容的时候, 实时把内容传递给父组件
const inputHandler = () => {
  // 触发自己的自定义事件
  emits('searchText', searchText.value)
}
</script>

<style scoped lang="scss">
.search {
  width: 100%;
  padding-left: 0;
}

.home-bar {
  background-color: red;
}

.cate_btn {
  font-size: 24px;
}

.login_btn {
  color: #fff;
}
</style>
